// pages/userInfoEdit/index.js
const App = getApp();
const { Dialog, Toast } = require("../../../../config/modal")
const utils = require("../../../../utils/util")
const { LOGIN, LOCATION } = require("../../../../config/login.js")
Page({

    /**
     * 页面的初始数据
     */
    data: {
        title: "个人资料",
        notice: "将带*号的信息填写完整，在接任务的时候会更好哟～",
        theamTextColor: App.globalData.theamTextColor,
        idCardMaxSize: 3145728,
        sex: {
            b: 0, // 女
            c: 1, // 男
            a: 2, // 未知
        },
        userInfo: {
            sex: 2,
            idCard: "",
            nickName: "",
            realName: "",
            alipayAccount: "",
            userPhone: "",
            wechatId: "",
            avatar: '',
            studentCode: "",
            schoolName: "",
            dorm: "",
            invitees: "",
            city: "",
        },
        idCard: [],
        rules:
        {
            realName: {
                msg: "请填写真名",
                required: true,
            },
            userPhone: { val: "", msg: "请填写电话", required: true },
            alipayAccount: { val: "", msg: "请输入支付宝账号", required: false },
            wechatId: { val: "", msg: "请填写微信账号", required: false },
            schoolName: { val: "", msg: "请填选择学校", required: true },
            studentCode: { val: "", msg: "请输入学号", required: false },
            dorm: { val: "", msg: "请输入宿舍", required: false },
            sex: { val: "", msg: "请输选择性别", required: false },
            city: { val: "", msg: "请选择城市", required: true },
        }

    },
    URL: {
        getMyInfo: "/customer/getMyInfo",
        save: "/task/publish",
        uploadAvatarUrl: "/customer/updateAvatar",
        saveUserInfo: "/customer/update"
    },
    page: {
        school: "/pages/school/index",
        userInfo: "/pages/tabbar/user/userInfoCenter/index",
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        wx.hideShareMenu();
        this.initMyInfo();
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },
    // 初始化用户信息
    initUserInfo() {
        let userInfo = App.$getUserInfo();
        if (!utils.isInvalid(userInfo)) {
            if (utils.isInvalid(userInfo.citySure)) {
                this.setData({
                    "userInfo.city": this.data.userInfo.city,
                })
            } else {
                this.setData({
                    "userInfo.city": userInfo.citySure,
                })
            }
            userInfo['schoolName'] = this.data.userInfo.schoolName;
        }
    },
    initMyInfo() {
        let userInfo = App.$getUserInfo();
        let formUserInfo = this.data.userInfo;
        App.$get(true, this.URL.getMyInfo, {}, res => {
            if (res.R) {
                let userDb = res.data;

                // 回显
                for (const formKey in formUserInfo) {
                    formUserInfo[formKey] = userDb[formKey];
                }

                // 同步更新本地缓存
                for (const formKey in userInfo) {
                    let val = userDb[formKey];
                    if (!utils.isInvalid(val)) {
                        userInfo[formKey] = val
                    }
                }
                userInfo['alipayAccount'] = utils.isInvalid(userDb['alipayAccount']) ? "" : userDb['alipayAccount'];
                userInfo['userPhone'] = utils.isInvalid(userDb['userPhone']) ? "" : userDb['userPhone'];
                userInfo['schoolName'] = utils.isInvalid(userDb['schoolName']) ? "" : userDb['schoolName'];
                App.$saveUserInfo(userInfo);
                console.log("更新本地缓存");

                // 邀请人的邀请码
                let invitees = App.$getData('invitees')

                console.log('邀请人', invitees)
                console.log('已有邀请人', userInfo.invitees == undefined ? '无' : userInfo.invitees)
                console.log('我的邀请码', userInfo.inviteCode)

                // console.log(utils.isInvalid(userInfo.invitees)
                //     && !utils.isInvalid(invitees)
                //     && userInfo.inviteCode != invitees)

                if (utils.isInvalid(userInfo.invitees)
                    && !utils.isInvalid(invitees)
                    && userInfo.inviteCode != invitees) {
                    res.data['invitees'] = invitees;
                }

                this.setData({
                    userInfo: formUserInfo,
                    "idCard": utils.isInvalid(res.data.idCard) ? [] : [{ name: '证件', url: res.data.idCard }]
                })

                this.initUserInfo();
            }
        })
    },


    toAuthLocation() {
        LOCATION.toAuthLocation((res) => {
            this.setData({
                "userInfo.city": res.citySure
            })
        })
    },
    onRealNameChange(e) {
        this.setData({
            'userInfo.realName': e.detail,
            'rules.realName.val': this.data.rules.realName.required ? utils.isInvalid(e.detail) ? this.data.rules.realName.msg : '' : ''
        })
    },
    onSexChange(e) {
        this.setData({
            'userInfo.sex': e.detail,
            'rules.userSex.val': this.data.rules.sex.required ? utils.isInvalid(e.detail) ? this.data.rules.sex.msg : '' : ''
        })
    },
    onWechatIdChange(e) {
        this.setData({
            'userInfo.wechatId': e.detail,
            'rules.wechatId.val': this.data.rules.wechatId.required ? utils.isInvalid(e.detail) ? this.data.rules.wechatId.msg : '' : ''
        })
    },
    onUserPhoneChange(e) {
        this.setData({
            'userInfo.userPhone': e.detail,
            'rules.userPhone.val': this.data.rules.userPhone.required ? utils.isInvalid(e.detail) ? this.data.rules.userPhone.msg : '' : ''
        })
    },
    onStudentCodeChange(e) {
        this.setData({
            'userInfo.studentCode': e.detail,
            'rules.studentCode.val': this.data.rules.studentCode.required ? utils.isInvalid(e.detail) ? this.data.rules.studentCode.msg : '' : ''
        })
    },
    onAlipayAccountChange(e) {
        this.setData({
            'userInfo.alipayAccount': e.detail,
            'rules.alipayAccount.val': this.data.rules.alipayAccount.required ? utils.isInvalid(e.detail) ? this.data.rules.alipayAccount.msg : '' : ''
        })
    },
    onSchoolNameChange(e) {
        this.setData({
            'userInfo.schoolName': e.detail,
            'rules.schoolName.val': this.data.rules.schoolName.required ? utils.isInvalid(e.detail) ? this.data.rules.schoolName.msg : '' : ''
        })
    },
    onInviteCodeChange(e) {
        this.setData({
            'userInfo.invitees': e.detail
        })
    },
    onDormChange(e) {
        this.setData({
            'userInfo.dorm': e.detail,
            'rules.dorm.val': this.data.rules.dorm.required ? utils.isInvalid(e.detail) ? this.data.rules.dorm.msg : '' : ''
        })
    },

    // 文件读取前
    fileBefore(event) {
        const { file, callback } = event.detail;
        callback(file.type === 'image');
    },

    // 扫描邀请码
    scanInviteCode() {
        let _this = this;
        Toast.loading({
            message: "解析中...",
            mask: true,
            duration: 60000
        })
        wx.scanCode({
            onlyFromCamera: false,
            scanType: ['qrCode'],
            success(res) {
                if (res.scanType != 'QR_CODE') {
                    Toast.fail("未检测到二维码")
                    return;
                }

                let detail = res.result
                Toast.clear({})
                if (utils.isInvalid(detail)) {
                    Toast.success("解析失败")
                    return;
                }
                _this.setData({
                    'userInfo.invitees': detail
                })
            },
            fail(e) {
                Toast.clear({})
            }
        })
    },

    fileOversize(event) {
        Dialog.alert({
            message: '证件只允许3M以内的照片',
            width: "250px",
            confirmButtonColor: "#D2691E",
            confirmButtonText: "关闭",
        }).then(() => {
        });
    },

    filepreview(event) {
    },
    fileDelete(event) {
        this.setData({
            "idCard": [],
            "userInfo.idCard": ''
        })
    },

    // 证件选择
    afterRead(event) {
        // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
        const { file } = event.detail;
        this.setData({
            "idCard": [{ url: file.url, name: "" }]
        })
        utils.fileToBase64(file.url, (base64) => {
            this.setData({
                "userInfo.idCard": base64
            })
        })
    },
    toSelectSchool() {
        App.$navigateTo(this.page.school, false)
    },
    submitUserInfo() {
        let userInfo = this.data.userInfo;
        let rules = this.data.rules;
        let errors = 0;
        for (const key in userInfo) {
            if (Object.hasOwnProperty.call(userInfo, key)) {
                const val = userInfo[key];
                if (!utils.isInvalid(rules[key]) && rules[key].required && utils.isInvalid(val)) {
                    let ruleKey = 'rules.' + key + '.val'
                    this.setData({
                        [ruleKey]: rules[key].msg
                    })
                    ++errors;
                }
            }
        }

        // if(utils.isInvalid(userInfo.idCard)){
        //     Toast("请选择学生证件照")
        //     return;
        // }

        if (errors > 0) {
            return;
        }
        delete userInfo['avatar']
        App.$post(true, this.URL.saveUserInfo, userInfo, res => {
            if (res.R) {
                this.initMyInfo();
                App.$removeStore('invitees')
                Dialog.alert({
                    message: '信息已保存',
                    width: "250px",
                    confirmButtonColor: "#D2691E",
                    confirmButtonText: "确定",
                }).then(() => {
                    //App.$navigateTo(this.page.userInfo, false);
                    wx.navigateBack({})
                })
            }
        })
    },
    uploadAvatar() {
        let _this = this
        let sourceAvatar = this.data.userInfo.avatar
        wx.chooseImage({
            count: 1,
            success: function (res) {
                const tempFilePaths = res.tempFilePaths[0]
                _this.setData({
                    'userInfo.avatar': tempFilePaths
                })
                let base64 = utils.fileToBase64Sync(tempFilePaths);
                App.$post(true, _this.URL.uploadAvatarUrl, { avatar: base64 }, res => {
                    if (!res.R) {
                        _this.setData({
                            'userInfo.avatar': sourceAvatar
                        })
                        return;
                    }
                    let userInfo = App.$getUserInfo();
                    userInfo['avatar'] = res.data + "?v=" + new Date().getTime();
                    App.$saveUserInfo(userInfo);
                })
            }
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },
    goBack() {
        wx.navigateBack({})
    },


    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})
